package com.aion.jirc.util;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * Date: 11-02-06
 * Time: 03:36
 *
 * @author Aion
 */
public class IRCStringUtils {

    // \\p{Cntrl} replaces this: \\x1f|\\x02|\\x12|\\x0f|\\x16|\\x03  (useful)
    private static final Pattern CTRL_CODES_PATTERN = Pattern.compile(
            "\\p{Cntrl}(?:\\d{1,2}(?:,\\d{1,2})?)?");

    /**
     * Converts control code characters into associated html characters.
     *
     * @param input
     *          the input to convert into HTML
     * @return the input converted into HTML
     */
    public static String convertToHTML(String input) {
        input = input.replaceAll("&", "&amp;");
        input = input.replaceAll(">", "&gt;");
        input = input.replaceAll("<", "&lt;");
        StringBuffer sb = new StringBuffer();
        ArrayList<String> list = new ArrayList<String>();
        for (char chr : input.toCharArray()) {
            String tag = getHTMLTagName(chr);
            if (!tag.isEmpty()) {
                String closedTag = "</".concat(tag).concat(">");
                if (list.contains(closedTag)) {
                    list.remove(closedTag);
                    sb.append(closedTag);
                    continue;
                }
                list.add(closedTag);
                if (tag.equalsIgnoreCase("span")) {
                    sb.append("<span style=\"color:#");
                    sb.append(Colors.WHITE).append("; background-color:#");
                    sb.append(Colors.BLACK).append("\">");
                } else {
                    sb.append("<").append(tag).append(">");
                }
            } else {
                sb.append(chr);
            }
        }
        for (int i = list.size() - 1; i >= 0; i--) {
            sb.append(list.get(i));
        }
        return stripControlCodes(sb.toString());
    }

    /**
     * Gets the HTML tag name for the given character.
     *
     * @param chr
     *          the character to return the HTML tag for
     * @return the HTML tag name for the given <code>char</code> or an empty <code>String</code>
     */
    private static String getHTMLTagName(char chr) {
        switch (chr) {
            case Colors.CTRL_B: return "b";
            case Colors.CTRL_I: return "i";
            case Colors.CTRL_R: return "span";
            case Colors.CTRL_U: return "u";
            default: return "";
        }
    }

    /**
     * Strips out all control codes.
     *
     * @param input
     *          the input to remove control codes from
     * @return stripped form of the input
     */
    public static String stripControlCodes(String input) {
        Matcher matcher = CTRL_CODES_PATTERN.matcher(input);
        return matcher.replaceAll("");
    }

}